/****************************************************************************
 * Copyright (C) 2011
 * by Dj_Skual
 *
 * This software is provided 'as-is', without any express or implied
 * warranty. In no event will the authors be held liable for any
 * damages arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any
 * purpose, including commercial applications, and to alter it and
 * redistribute it freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you
 * must not claim that you wrote the original software. If you use
 * this software in a product, an acknowledgment in the product
 * documentation would be appreciated but is not required.
 *
 * 2. Altered source versions must be plainly marked as such, and
 * must not be misrepresented as being the original software.
 *
 * 3. This notice may not be removed or altered from any source
 * distribution.
 *
 * emiibrowser.cpp
 *
 * for SaveGame Manager GX 2011
 ***************************************************************************/
#include <algorithm>

//#include "../../FileOperations/DirList.h"
//#include "../../FileOperations/fileops.h"
#include "emiibrowser.h"

EMiiBrowser::EMiiBrowser()
	:MiiBrowser()
{
	SearchChars.clear();
	
	//!Reset and prepare browser
	ResetBrowser();
	
	curENandPath = "";
}

static bool NameSortCallback(const MiiStruct *a, const MiiStruct *b)
{
	return (stricmp((wstr2str(((MiiStruct *)a)->name)).c_str(), (wstr2str(((MiiStruct *)b)->name)).c_str()) < 0);
}

void EMiiBrowser::GetList(std::string emuPath)
{
	ResetBrowser();
	
	//! get MiiDB emulate path
	std::string EmuMiiDBPath = emuPath;
	EmuMiiDBPath += MII_FILE;
	
	FILE *fp = fopen(EmuMiiDBPath.c_str(),"rb");
	if(fp == NULL)
		return;	
	
	//! Get Mii data
	u32 tsize = (MII_SIZE * MII_MAX) + MII_HEADER;
	
	char* miidata = (char*)memalign(32, tsize);
	memset(miidata, 0, sizeof(tsize));
	
	if (fread(miidata, 1, tsize, fp) != tsize)
	{
		fclose(fp);
		free(miidata);
		miidata = NULL;
		return;
	}
	fclose(fp);
	
	if (miidata[0] != 'R' || miidata[1] != 'N' || miidata[2] != 'O' || miidata[3] != 'D')
	{
		gprintf("Mii version %c%c%c%c is not compatible with libmii\n", miidata[0], miidata[1], miidata[2], miidata[3]);
		free(miidata);
		miidata = NULL;
		return;
	}
	else
	{
		u32 cnt = 0;
		for (int pos = 0; pos < MII_MAX; pos++)
		{
			if(cnt >= browserList.size())
				AddEntry();
			
			if(!MiiTools::GetNandInfos(pos, miidata, browserList[cnt]))
				RemoveEntry(cnt);
			else
				cnt++;
		}
	}
	
	//! Free memory
	if (miidata)
		free(miidata);
	
	if(!browserList.empty())
		curENandPath = emuPath;
	
	std::sort(browserList.begin(), browserList.end(), NameSortCallback);
}
